import React from "react";
import cover from "../../assets/image/注册.webp";
import { Form, Input, Button, message } from "antd";
import UserCom from "../../components/UserCom";
import api from "../../api";
const Register = (props) => {
  const [form] = Form.useForm();
  const ruleRequire = { required: true, message: "此项不能为空" };
  const validatePsw = ({ getFieldValue }) => {
    return {
      validator: (_, value) => {
        if (!value || getFieldValue("password") === value) {
          return Promise.resolve();
        }
        return Promise.reject(new Error("两次输入密码不一致，请重新输入!"));
      },
    };
  };
  const register = async (values) => {
    const res = await api.register({ username: values.username, password: values.password, nickname: "" });
    if (res.message === "操作成功") {
      message.success("注册成功");
      props.history.push("/login");
    } else {
      message.warning(res.data);
    }
  };
  return (
    <UserCom cover={cover}>
      <div className="login-main">
        <div className="login-title">访客注册</div>
        <Form onFinish={register} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} form={form} name="testForm">
          <Form.Item name="username" label="账号" rules={[ruleRequire]}>
            <Input placeholder="请输入用户名"></Input>
          </Form.Item>
          <Form.Item name="password" label="密码" rules={[ruleRequire]}>
            <Input.Password placeholder="请输入密码"></Input.Password>
          </Form.Item>
          <Form.Item name="confirmPsw" label="确认" dependencies={["password"]} validateTrigger="onBlur" rules={[ruleRequire, validatePsw]}>
            <Input.Password placeholder="请再次输入密码"></Input.Password>
          </Form.Item>
          <div className="login-btn-box">
            <Button type="primary" htmlType="submit">
              注册
            </Button>
          </div>
        </Form>
        <div
          className="or-box"
          onClick={() => {
            props.history.push("/login");
          }}
        >
          Or 去登录
        </div>
      </div>
    </UserCom>
  );
};

export default Register;
